/*
 * Copyright (C) 2022 xuexiangjys(xuexiangjys@163.com)
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *       http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 *
 */

package cn.kcrx.autoweightapp.fragment

import android.speech.tts.TextToSpeech
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.fragment.app.viewModels
import androidx.lifecycle.lifecycleScope
import androidx.recyclerview.widget.DefaultItemAnimator
import androidx.recyclerview.widget.LinearLayoutManager
import cn.kcrx.autoweightapp.R
import cn.kcrx.autoweightapp.core.BaseFragment
import cn.kcrx.autoweightapp.databinding.FragmentMainAutoweightBinding
import cn.kcrx.autoweightapp.fragment.adapter.CashWeightRecordAdapter
import cn.kcrx.autoweightapp.fragment.viewmodes.FramentMainAutoViewModel
import cn.kcrx.autoweightapp.models.NewCashBoxSetting
import cn.kcrx.autoweightapp.utils.AutoAcceptButtomHelper
import cn.kcrx.autoweightapp.utils.SerialUtil
import cn.kcrx.autoweightapp.utils.shanShuo
import cn.kcrx.autoweightapp.utils.slideIn
import com.xuexiang.xaop.annotation.MainThread
import com.xuexiang.xaop.annotation.SingleClick
import com.xuexiang.xpage.annotation.Page
import com.xuexiang.xpage.utils.TitleBar
import com.xuexiang.xui.utils.CountDownButtonHelper
import com.xuexiang.xui.utils.ViewUtils
import com.xuexiang.xutil.app.AppUtils
import dagger.hilt.android.AndroidEntryPoint
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.GlobalScope
import kotlinx.coroutines.launch
import kotlinx.coroutines.withContext
import mu.KotlinLogging
import java.util.*
@AndroidEntryPoint
@Page(name = "原封箱整托盘称重分析报警系统")
class FragmentMainAuto :BaseFragment<FragmentMainAutoweightBinding>(){
    private val logger=KotlinLogging.logger {  }
    private val viewmodel:FramentMainAutoViewModel by viewModels()
    private val serialUtil=SerialUtil()
    private val adapter=CashWeightRecordAdapter()
    var autoAcceptButtomHelper:AutoAcceptButtomHelper?=null
   // private var mCountDownHelper: CountDownButtonHelper? = null
    //语音
    private lateinit var  textToSpeech: TextToSpeech

    override fun viewBindingInflate(
        inflater: LayoutInflater,
        container: ViewGroup
    ): FragmentMainAutoweightBinding {
      return FragmentMainAutoweightBinding.inflate(inflater,container,false)
    }

    override fun initTitle(): com.xuexiang.xui.widget.actionbar.TitleBar? {
        return super.initTitle()?.setTitleSize(48f)
    }

    override fun initViews() {
        initTTS()
        binding!!.rvBoxrecord.layoutManager= LinearLayoutManager(context)
        binding!!.rvBoxrecord.adapter=adapter
        binding!!.rvBoxrecord.itemAnimator=DefaultItemAnimator()
        viewmodel.todayRecords.observe(viewLifecycleOwner){
            logger.error { "recordList size=${it.size}" }
            adapter.submitList(it)
        }
        binding!!.tvVersion.text="版本号:V${AppUtils.getAppVersionName()}"
        viewmodel.mainWeight.observe(viewLifecycleOwner){
             binding!!.tvMainWeight.text=String.format("%.2f", it)
             binding!!.tvMainWeight.slideIn()
        }
        viewmodel.mainWeightRange.observe(viewLifecycleOwner){
            binding!!.tvMainWeightrange.text=it.toString()
            binding!!.tvMainWeightrange.slideIn()
        }
        viewmodel.mainTestWeight.observe(viewLifecycleOwner){
            binding!!.tvTestweight.text=it.toString()
            binding!!.tvTestweight.shanShuo()
        }
        autoAcceptButtomHelper= AutoAcceptButtomHelper(binding!!.btnAccept,10)

        viewmodel.mainTestResult.observe(viewLifecycleOwner){
            binding!!.tvTestresult.text=it
            textToSpeech.speak("$it ${viewmodel.mainTestWeight.value.toString()}公斤",TextToSpeech.QUEUE_FLUSH,null)
            if(it=="正常"){
                binding!!.tvTestresult.setTextColor(resources.getColor(R.color.xui_btn_green_normal_color))
                binding!!.btnAccept.visibility=View.VISIBLE
                autoAcceptButtomHelper!!.start()//开始自动计时
            }else{
                binding!!.tvTestresult.setTextColor(resources.getColor(R.color.xui_config_color_red))
            }
            binding!!.tvTestresult.shanShuo()
        }
        serialUtil.serialPortManager?.setOnSerialPortDataListener {
            try {
                    val weights=String(it)
                    weights.split("\r\n").forEach {weightstr->
                    if(weightstr.startsWith("wn")&&weightstr.endsWith("kg")){
                        //logger.error{"接收到测量重量=${weightstr}"}
                            val weightTest=weightstr.replace("wn","").replace("kg","").toFloat()
                       requireActivity().runOnUiThread {
                           viewmodel.setMainTestWeight(weightTest)
                       }
                    }
                }
            }catch (e:Exception){
                logger.error("串口接收数据异常",e)
            }
        }


       setGoodweight()
    }

    @SingleClick
    private fun autoAccepteFun(it: View?) {
        viewmodel.insertDBRecord(cashnamenow)
    }
    //测试
    private fun setGoodweight() {
        lifecycleScope.launch(Dispatchers.Main) {
          val weight=  withContext(Dispatchers.IO){
                Thread.sleep(10000)
                550f
            }
            viewmodel.setMainTestWeight(weight)
        }
    }
    var cashnamenow="100元"
    override fun initListeners() {
        super.initListeners()
       binding!!.radioGroupCash.setOnCheckedChangeListener { _, i ->
           when(i)
           {
               binding!!.rbtn100.id-> {
                   viewmodel.setMainWeight(NewCashBoxSetting.settinglist[0].weight)
                   viewmodel.setMainWeightRange(NewCashBoxSetting.settinglist[0].weightrange)
                   viewmodel.setMainTestWeight(0.0f)
                   cashnamenow="100元"
               }
               binding!!.rbtn50.id-> {
                   viewmodel.setMainWeight(NewCashBoxSetting.settinglist[1].weight)
                   viewmodel.setMainWeightRange(NewCashBoxSetting.settinglist[1].weightrange)
                   viewmodel.setMainTestWeight(0.0f)
                   cashnamenow="50元"
               }
               binding!!.rbtn20.id-> {
                  viewmodel.setMainWeight(NewCashBoxSetting.settinglist[2].weight)
                   viewmodel.setMainWeightRange(NewCashBoxSetting.settinglist[2].weightrange)
                   viewmodel.setMainTestWeight(0.0f)
                   cashnamenow="20元"
               }
               binding!!.rbtn10.id-> {
                  viewmodel.setMainWeight(NewCashBoxSetting.settinglist[3].weight)
                   viewmodel.setMainWeightRange(NewCashBoxSetting.settinglist[3].weightrange)
                   viewmodel.setMainTestWeight(0.0f)
                   cashnamenow="10元"
               }
               binding!!.rbtn5.id-> {
                   viewmodel.setMainWeight(NewCashBoxSetting.settinglist[4].weight)
                   viewmodel.setMainWeightRange(NewCashBoxSetting.settinglist[4].weightrange)
                   viewmodel.setMainTestWeight(0.0f)
                   cashnamenow="5元"
               }
               binding!!.rbtn1.id-> {
                   viewmodel.setMainWeight(NewCashBoxSetting.settinglist[5].weight)
                   viewmodel.setMainWeightRange(NewCashBoxSetting.settinglist[5].weightrange)
                   viewmodel.setMainTestWeight(0.0f)
                   cashnamenow="1元"
               }
           }

       }
        binding!!.btnAccept.setOnClickListener {
            it.isEnabled=false
            autoAcceptButtomHelper?.cancel()
            autoAccepteFun(it)
        }
    }

    override fun onDestroyView() {
        super.onDestroyView()
        serialUtil.serialPortManager?.closeSerialPort()
        if (autoAcceptButtomHelper != null) {
            autoAcceptButtomHelper!!.recycle()
        }
    }
    override fun onDestroy() {
        super.onDestroy()

    }
    fun initTTS(){
        textToSpeech=TextToSpeech(requireContext()
        ) { status ->
            if (status == TextToSpeech.SUCCESS){
                textToSpeech.setLanguage(Locale.CHINA).also {
                    if (it != TextToSpeech.LANG_COUNTRY_AVAILABLE
                        && it != TextToSpeech.LANG_AVAILABLE
                    ) {
                        logger.error("TTS暂时不支持这种语音的朗读！")
                    }
                }
            }
        }
    }
}